Skip to content

Automated Test: plugins/rename-instrumentation-middleware-to-metrics-middleware #337

Conversation

admin-coderabbit
Copy link
Owner

@admin-coderabbit admin-coderabbit commented Feb 4, 2026

This pull request was automatically created by @coderabbitai/e2e-reviewer.

Batch created pull request.

Summary by CodeRabbit

  • Refactor
    • Improved logging infrastructure for plugin operations with enhanced contextual information capture.
    • Streamlined log output formatting for cleaner, more focused plugin diagnostic data.
    • Optimized middleware chain ordering for better logging and metrics collection.

…are (#76186)

* Plugins: Chore: Renamed instrumentation middleware to metrics middleware

* Removed repeated logger attributes in middleware and contextual logger

* renamed loggerParams to logParams

* PR review suggestion

* Add contextual logger middleware

* Removed unused params from logRequest

* Removed unwanted changes

* Safer FromContext method

* Removed traceID from logParams
@coderabbit-eval
Copy link

coderabbit-eval bot commented Feb 4, 2026

📝 Walkthrough

Walkthrough

The changes add a FromContext method to logger interfaces and implementations, replace interface{} with the any alias across logger signatures, introduce a new contextual logger middleware that enriches request context with attributes, refactor the logger middleware to use context-based logging, rename InstrumentationMiddleware to MetricsMiddleware, and reorder the plugin client middleware chain.

Changes

Cohort / File(s) Summary
Logger Interface and Implementations
pkg/plugins/log/ifaces.go, pkg/plugins/log/fake.go, pkg/plugins/log/logger.go
Added FromContext(ctx context.Context) Logger method to Logger interface and implementations. Replaced all interface{} variadic parameters with any across Logger and PrettyLogger method signatures (New, Debug, Info, Warn, Error, and formatting variants).
Contextual Logger Middleware
pkg/services/pluginsintegration/clientmiddleware/contextual_logger_middleware.go
New middleware that enriches request context with contextual attributes (endpoint, pluginId, dsName, dsUID, uname) via log.WithContextualAttributes before delegating to the next client. Instruments QueryData, CallResource, CheckHealth, and CollectMetrics operations.
Logger Middleware Refactoring
pkg/services/pluginsintegration/clientmiddleware/logger_middleware.go
Simplified logRequest to be context-driven. Removed pluginCtx and endpoint parameters; now uses FromContext(ctx).Info() for logging. Eliminates plugin-specific log fields (pluginId, endpoint, traceID, dsName, dsUID, uname) in favor of context-based attributes.
Metrics Middleware Rename and Cleanup
pkg/services/pluginsintegration/clientmiddleware/metrics_middleware.go, pkg/services/pluginsintegration/clientmiddleware/metrics_middleware_test.go
Renamed InstrumentationMiddleware to MetricsMiddleware with updated constructors and method receivers. Removed instrumentContext helper and unused log import, shifting context enrichment responsibility to the new ContextualLoggerMiddleware.
Middleware Chain Registration
pkg/services/pluginsintegration/pluginsintegration.go
Updated middleware registration to replace instrumentation middleware with metrics middleware and insert the new contextual logger middleware immediately after it, establishing new middleware ordering.

Sequence Diagram

sequenceDiagram
    participant Client as Plugin Client
    participant CLM as ContextualLoggerMiddleware
    participant LM as LoggerMiddleware
    participant MM as MetricsMiddleware
    participant Backend as Backend Plugin

    Client->>CLM: QueryData(ctx, req)
    CLM->>CLM: Enrich context with attributes<br/>(endpoint, pluginId, dsName, etc.)
    CLM->>LM: QueryData(ctx, req)
    LM->>LM: Log context-aware details<br/>using FromContext(ctx).Info()
    LM->>MM: QueryData(ctx, req)
    MM->>MM: Instrument metrics<br/>(request size, duration)
    MM->>Backend: QueryData(ctx, req)
    Backend-->>MM: response/error
    MM-->>LM: response/error
    LM-->>CLM: response/error
    CLM-->>Client: response/error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 Context flows through our loggers now,
With attributes attached and a mighty vow!
The middleware chain rearranged just right,
From context we craft each log's delight!
Renaming and typing, all cleaned up bright! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Title check ⚠️ Warning The title describes a refactoring focused on renaming InstrumentationMiddleware to MetricsMiddleware, which is only one aspect of the broader changes that include new logger interface methods, context-based logging, and middleware restructuring. Revise the title to reflect the primary changes more accurately, such as 'Add FromContext method to logger interfaces and restructure plugin middleware' or similar to better represent the full scope of the changeset.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch plugins/rename-instrumentation-middleware-to-metrics-middleware

Comment @coderabbit eval help to get the list of available commands and usage tips.

@coderabbit-eval coderabbit-eval bot closed this Feb 4, 2026
Copy link

@coderabbit-eval coderabbit-eval bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/plugins/log/fake.go (1)

3-48: ⚠️ Potential issue | 🟡 Minor

Keep TestLogger log capture when using FromContext.
Returning a fresh TestLogger means logs emitted via FromContext won't be visible on the original instance, which can break assertions on captured logs. Consider returning the same logger (or sharing log storage).

🔧 Suggested adjustment
-func (f *TestLogger) FromContext(_ context.Context) Logger {
-	return NewTestLogger()
-}
+func (f *TestLogger) FromContext(_ context.Context) Logger {
+	return f
+}
🤖 Fix all issues with AI agents
In
`@pkg/services/pluginsintegration/clientmiddleware/contextual_logger_middleware.go`:
- Around line 26-36: The middleware currently attaches user identifiers to logs
by adding pCtx.User.Login as "uname" in instrumentContext; remove or gate this
PII: delete the uname entry (remove the pCtx.User.Login append) or wrap it
behind an explicit privacy flag/anonymization check (e.g., only append a
pseudonymized user id or when a config like allowLogUsernames is true) before
calling log.WithContextualAttributes, ensuring instrumentContext and the usage
of pCtx.User.Login are the only places changed.

Comment on lines +26 to +36
// instrumentContext adds a contextual logger with plugin and request details to the given context.
func instrumentContext(ctx context.Context, endpoint string, pCtx backend.PluginContext) context.Context {
p := []any{"endpoint", endpoint, "pluginId", pCtx.PluginID}
if pCtx.DataSourceInstanceSettings != nil {
p = append(p, "dsName", pCtx.DataSourceInstanceSettings.Name)
p = append(p, "dsUID", pCtx.DataSourceInstanceSettings.UID)
}
if pCtx.User != nil {
p = append(p, "uname", pCtx.User.Login)
}
return log.WithContextualAttributes(ctx, p)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Avoid logging user identifiers by default.
Line 33–35 adds uname from pCtx.User.Login; that’s PII and can violate privacy/retention policies. Prefer removing it or gating behind explicit config/anonymization.

🔧 Proposed fix (remove username from context)
 func instrumentContext(ctx context.Context, endpoint string, pCtx backend.PluginContext) context.Context {
 	p := []any{"endpoint", endpoint, "pluginId", pCtx.PluginID}
 	if pCtx.DataSourceInstanceSettings != nil {
 		p = append(p, "dsName", pCtx.DataSourceInstanceSettings.Name)
 		p = append(p, "dsUID", pCtx.DataSourceInstanceSettings.UID)
 	}
-	if pCtx.User != nil {
-		p = append(p, "uname", pCtx.User.Login)
-	}
 	return log.WithContextualAttributes(ctx, p)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// instrumentContext adds a contextual logger with plugin and request details to the given context.
func instrumentContext(ctx context.Context, endpoint string, pCtx backend.PluginContext) context.Context {
p := []any{"endpoint", endpoint, "pluginId", pCtx.PluginID}
if pCtx.DataSourceInstanceSettings != nil {
p = append(p, "dsName", pCtx.DataSourceInstanceSettings.Name)
p = append(p, "dsUID", pCtx.DataSourceInstanceSettings.UID)
}
if pCtx.User != nil {
p = append(p, "uname", pCtx.User.Login)
}
return log.WithContextualAttributes(ctx, p)
// instrumentContext adds a contextual logger with plugin and request details to the given context.
func instrumentContext(ctx context.Context, endpoint string, pCtx backend.PluginContext) context.Context {
p := []any{"endpoint", endpoint, "pluginId", pCtx.PluginID}
if pCtx.DataSourceInstanceSettings != nil {
p = append(p, "dsName", pCtx.DataSourceInstanceSettings.Name)
p = append(p, "dsUID", pCtx.DataSourceInstanceSettings.UID)
}
return log.WithContextualAttributes(ctx, p)
}
🤖 Prompt for AI Agents
In
`@pkg/services/pluginsintegration/clientmiddleware/contextual_logger_middleware.go`
around lines 26 - 36, The middleware currently attaches user identifiers to logs
by adding pCtx.User.Login as "uname" in instrumentContext; remove or gate this
PII: delete the uname entry (remove the pCtx.User.Login append) or wrap it
behind an explicit privacy flag/anonymization check (e.g., only append a
pseudonymized user id or when a config like allowLogUsernames is true) before
calling log.WithContextualAttributes, ensuring instrumentContext and the usage
of pCtx.User.Login are the only places changed.

Sign in to join this conversation on GitHub.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant